package com.xbniao.gcfs.common.util.validation;

import com.xbniao.gcfs.common.util.StringLengthUtil;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * @Author:wangbin.
 * @Description.
 * @Date:Created in 17:05 2017/9/23.
 * @Modified By:
 */
public class CannotContainSpacesValidator implements ConstraintValidator<CannotContainSpaces,String>{
    private int len;
    /**
     * 初始参数,获取注解中length的值
     */
    @Override
    public void initialize(CannotContainSpaces arg0) {
        this.len = arg0.max();
    }

    @Override
    public boolean isValid(String str, ConstraintValidatorContext constraintValidatorContext) {
        if(StringLengthUtil.length(str) <= len){
                return true;
        }else{
            constraintValidatorContext.disableDefaultConstraintViolation();//禁用默认的message的值
            //重新添加错误提示语句
            String errorMessage = constraintValidatorContext.getDefaultConstraintMessageTemplate();
            constraintValidatorContext
                    .buildConstraintViolationWithTemplate(errorMessage).addConstraintViolation();
        }
        return false;
    }
}
